package com.chixing.ih.module.task.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.chixing.ih.config.AlipayConfig;
import com.chixing.ih.module.task.mapper.OrderMapper;
import com.chixing.ih.module.task.pojo.ChargeBack;
import com.chixing.ih.module.task.pojo.DTO.TaskShowDTO;
import com.chixing.ih.module.task.pojo.Order;
import com.chixing.ih.module.task.service.IChargeBackService;
import com.chixing.ih.module.task.service.IOrderService;
import com.chixing.ih.module.task.service.IPayService;
import com.chixing.ih.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Random;

/**
 * 目的:
 *
 * @author ：zcw
 * @version: 1.0  2020/10/13 19:52
 */
@Service
@Slf4j
public class PayServiceImpl implements IPayService {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private TaskServiceImpl taskService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IChargeBackService chargeBackService;


    @Override
    public void pay(Long orderId, HttpServletResponse response, HttpServletRequest request) throws AlipayApiException
            , IOException {
        // 设置编码格式
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),
                alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getPublicKey(),
                alipayConfig.getSignType());

        //设置请求参数
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        aliPayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        aliPayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());
        Order orders = orderMapper.getOne(orderId);

        //商户订单号，后台可以写一个工具类生成一个订单号，必填
        String order_number = orders.getOrderNum();

        TaskShowDTO dto = taskService.findOne(orders.getTaskId());

        //付款金额，从前台获取，必填
        String total_amount = orders.getSalary().toString();
        //订单名称/标题，可自定义
        String subject = dto.getMandateTitle();

        aliPayRequest.setBizContent("{\"out_trade_no\":\"" + order_number + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(aliPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //输出
        out.println(result);//以下写自己的订单代码
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers", "*");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        log.info(result);

    }
//
//    @Override
//    public void refund(Order order, HttpServletResponse response, HttpSession session) throws IOException,
//            AlipayApiException {
//        // 设置编码格式
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        //获得初始化的AlipayClient
//        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getAppId(),
//                alipayConfig.getPrivateKey(),
//                alipayConfig.getFormat(), alipayConfig.getCharset(), alipayConfig.getPublicKey(),
//                alipayConfig.getSignType());        //设置请求参数
//        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
//        //商户订单号，必填
//        String out_trade_no = order.getOrderNum();
//        //需要退款的金额，该金额不能大于订单金额，必填
//        String refund_amount = order.getSalary().toString();
//        //标识一次退款请求，同一笔交易多次退款需要保证唯一。如需部分退款，则此参数必传；不传该参数则代表全额退款
//        String out_request_no = new Random(1).toString();
//        //退款原因
//        String reason_for_refund = "测试";
//        // 字符转义很重要
//        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
//                + "\"refund_amount\":\"" + refund_amount + "\","
//                + "\"out_request_no\":\"" + out_request_no + "\"}");
//        //请求
//        String result = alipayClient.execute(alipayRequest).getBody();
//        //输出
//        out.println(result);//以下写自己的订单退款代码
//
//        ChargeBack chargeBack = new ChargeBack();
//
//        chargeBack.setOrderId(Long.parseLong(out_trade_no));
//        chargeBack.setCreateTime(new Date());
//        chargeBack.setRefundAmount(Double.parseDouble(refund_amount));
//        chargeBack.setReasonForRefund(reason_for_refund);
//        chargeBack.setOutRequestNo(Integer.parseInt(out_request_no));
//
//        chargeBackService.saveOne(chargeBack);
//    }
}
